package com.lahuan.rpc.protocol.netty.server;

import com.lahuan.rpc.protocol.tcp.CustomTcpDecoder;
import com.lahuan.rpc.protocol.tcp.CustomTcpEncoder;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.CopyOnWriteArrayList;

@Slf4j
public class NettyServer {
    static  CopyOnWriteArrayList<Integer> started = new CopyOnWriteArrayList<>();

    public synchronized static void start(Integer port, ServerInvoker invoker) throws Exception {
           if(started.contains(port)){
               //每个端口只绑定第一次
               return;
           }

        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap b = new ServerBootstrap();
            b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                                @Override  
                                public void initChannel(SocketChannel ch) throws Exception {
                                    ch.pipeline().addLast(new CustomTcpEncoder());
                                    ch.pipeline().addLast(new CustomTcpDecoder());

                                    ch.pipeline().addLast(new ServerInboundHandler(invoker));
                                }  
                            }).option(ChannelOption.SO_BACKLOG, 128)
                    .childOption(ChannelOption.SO_KEEPALIVE, true);

            ChannelFuture f = b.bind(port).sync();
            System.out.println(" NettyServer start  :"+port);
            started.add(port);
            f.channel().closeFuture().sync();
            System.out.println("NettyServer init end");
        } finally {  
            workerGroup.shutdownGracefully();  
            bossGroup.shutdownGracefully();  
        }  
    }  
  

}